package doublepoint;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/4 0:19
 * https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
 */
public class GetIntersectionNode {

    class ListNode {
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }

    /**
     * 设交集链表长c,链表1除交集的长度为a，链表2除交集的长度为b，有
     *
     * a + c + b = b + c + a
     * 若无交集，则a + b = b + a
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode h1 = headA;
        ListNode h2 = headB;
        while (h1 != h2) {
            h1 = h1 == null ? headB : h1.next;
            h2 = h2 == null ? headA : h2.next;
        }
        return h1;
    }

    /**
     *两列表长度相减
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        int lenA = 0, lenB = 0;
        ListNode nodeA = headA;
        ListNode nodeB = headB;
        while (nodeA != null) {
            nodeA = nodeA.next;
            lenA++;
        }
        while (nodeB != null) {
            nodeB = nodeB.next;
            lenB++;
        }
        nodeA = headA;
        nodeB = headB;
        //curA当长链表
        if (lenB > lenA) {
            //交换长度
            int tempLen = lenA;
            lenA = lenB;
            lenB = tempLen;
            //交换链表（交换名称）
            ListNode tempNode = nodeA;
            nodeA = nodeB;
            nodeB = tempNode;
        }
        int gap = lenA -lenB;
        while (gap-- > 0) {
            nodeA = nodeA.next;
        }
        while (nodeA != null) {
            if (nodeA == nodeB) {
                return nodeA;
            }
            nodeA = nodeA.next;
            nodeB = nodeB.next;
        }
       return null;
    }

    public static void main(String[] args) {

    }
}
